#!/usr/bin/env sh
#author:ziyu
#date:2020-11-26 12:40
cd /home/ec2-user/build/az-web/azmobileus || exit;

imagesRes=$(sudo docker images | awk '$0 ~ /ziyu\/azweb-mobile-us/ {print $1}')

envResult=$(echo "${WORKSPACE}" | grep "autotest-azweb-mobile-us-prod.dev")

if [ "$envResult" != "" ]; then
  autoEnv='生产'
else
  autoEnv='P'
fi

sudo python3 /var/job/konck_notice.py GRT:1TVjsOtQKlS "'test'('test')AZWEB-${autoEnv}-Mobile-US自动化测试 开始测试"

buildImage() {
  sudo docker build -t ziyu/azweb-mobile-us:v1.0 .
}

runImage() {
  sudo docker run --rm --name azweb-mobile-us \
      -v "$PWD"/logs/:/user/src/test/az-web/azmobileus/logs/ \
      -v "${WORKSPACE}"/allure-results/:/user/src/test/az-web/azmobileus/reports/ \
      -v "$PWD"/screenshot/:/user/src/test/az-web/azmobileus/screenshot/ \
      -P ziyu/azweb-mobile-us:v1.0 "$1" "$2" "$3" "$4" "$5" "$6" "$7"
}

generateReport() {
  allure generate "${WORKSPACE}"/allure-results/ -o "${WORKSPACE}"/allure-report/ --clean
  cp -r "${WORKSPACE}"/allure-report/history/ "${WORKSPACE}"/allure-results/
  failed=$(sudo cat "${WORKSPACE}"/allure-report/widgets/summary.json \
        | awk -F: 'NR==5 {print $2}' | awk -F',' '{print $1}')
  broken=$(sudo cat "${WORKSPACE}"/allure-report/widgets/summary.json \
        | awk -F: 'NR==6 {print $2}' | awk -F',' '{print $1}')
  passed=$(sudo cat "${WORKSPACE}"/allure-report/widgets/summary.json \
        | awk -F: 'NR==8 {print $2}' | awk -F',' '{print $1}')
  total=$(sudo cat "${WORKSPACE}"/allure-report/widgets/summary.json \
        | awk -F: 'NR==10 {print $2}' | awk -F',' '{print $1}')
  sudo python3 /var/job/konck_notice.py GRT:1TVjsOtQKlS \
        "'test'('test')AZWEB-${autoEnv}-Mobile-US自动化测试已完成 TOTAL:${total} PASS:${passed} FAIL:${failed} BROKEN:${broken}"
}

if [ "ziyu/azweb-mobile-us" = "${imagesRes}" ]; then
  echo "ziyu/azweb-mobile-us:v1.0镜像存在，删除镜像并重新构建"
  sudo docker rm -f azweb-mobile-us
  sudo docker rmi -f ziyu/azweb-mobile-us:v1.0
  buildImage
  runImage "$1" "$2" "$3" "$4" "$5" "$6" "$7"
  generateReport
else
  echo "镜像不存在，直接构建ziyu/azweb-mobile-us:v1.0镜像"
  sudo docker rm -f azweb-mobile-us
  buildImage
  runImage "$1" "$2" "$3" "$4" "$5" "$6" "$7"
  generateReport
fi
